﻿Imports DevComponents.DotNetBar.Controls
Imports TNCBAL
Imports TNCDAL

Public Class ucFileManagement
    Private _objFileController As New FileController
    Private _objFormMain As frmMain
    'Cho biết File thuộc Export hay Import
    Private _enumFILE As enumFILE

    Private _objFile As tblFile ' Thông tin File
    Private _ucFileHBLGridView As ucFileHBLGridView
    Private _ucFileMBLGridView As ucFileMBLGridView

    Private currRow As Integer = -1 ' Current row in datagridview
    Private currTab As Integer = -1 ' Current tab in tabcontrol

    Public Sub New(ByVal frmMain As frmMain, ByVal eFILE As enumFILE)
        InitializeComponent()
        HTLibrary.DataGridViewHelper.DataGridView_InitEvent(dataGridViewFiles)
        'Thanh thêm ngày 15/3/2014
        HTLibrary.DataGridViewHelper.DataGridView_InitEvent(dgContainers)
        HTLibrary.DataGridViewHelper.DataGridView_InitEvent(gridSelling)
        HTLibrary.DataGridViewHelper.DataGridView_InitEvent(dtgBuying)
        'hết phần Thanh thêm ngày 15/3/2014
        _objFormMain = frmMain
        _enumFILE = eFILE

        'Chức năng dành cho hàng nhập
        If _enumFILE = enumFILE.Import Then
            btPrintAN.Visible = True
        Else
            btPrintAN.Visible = False
            btnPaymentVoucher.Location = btPrintAN.Location
        End If
    End Sub

    Private Sub ucFileManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SuperTabControlFile.SelectedTab = SuperTabControlFile.Tabs(0)
        InitSearchUserControl()
        FileStatusColumn_Initialize()

        BindingDataGridView()
        FormatDataGridView()
    End Sub

#Region "File DataGridView"

#Region "FileStatusColumns_Initialize"

    ''' <summary>
    ''' Initializes our File Status column
    ''' </summary>
    Private Sub FileStatusColumn_Initialize()
        Dim bcx As DataGridViewLabelXColumn = New DataGridViewLabelXColumn()
        bcx.Name = "FileStatus"
        bcx.HeaderText = "Status"
        bcx.TextAlignment = System.Drawing.StringAlignment.Center
        bcx.TextLineAlignment = StringAlignment.Center
        dataGridViewFiles.Columns.Insert(0, bcx)

        'AddHandler statusColumn.BeforeCellPaint, AddressOf FileStatusColumn_BeforeCellPaint
        If bcx IsNot Nothing Then
            ' Hook onto the BeforeCellPaint event so we can
            ' demonstrate cell customization

            AddHandler bcx.BeforeCellPaint, AddressOf FileStatusColumn_BeforeCellPaint
        End If
    End Sub

#Region "FileStatusColumns_BeforeCellPaint"
    ''' <summary>
    ''' Handles BeforeCellPaint events
    ''' </summary>
    ''' <param name="sender">DataGridViewButtonXColumn</param>
    ''' <param name="e">BeforeCellPaintEventArgs</param>
    Private Sub FileStatusColumn_BeforeCellPaint(ByVal sender As Object, ByVal e As BeforeCellPaintEventArgs)
        Try
            Dim bcx As DataGridViewLabelXColumn = TryCast(sender, DataGridViewLabelXColumn)
            If bcx IsNot Nothing Then
                Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle
                ' Set the label image
                If dataGridViewFiles.Rows(e.RowIndex).Cells("Status").Value = "-1" Then 'File bị hủy
                    dataGridViewFiles.Rows(e.RowIndex).Cells("FileStatus").ToolTipText = "File đã bị hủy"
                    bcx.Image = imageList1.Images("SecHigh")
                    DataGridViewCellStyle1.ForeColor = Color.LightGray ' System.Drawing.SystemColors.ControlText
                    dataGridViewFiles.Rows(e.RowIndex).DefaultCellStyle = DataGridViewCellStyle1
                ElseIf dataGridViewFiles.Rows(e.RowIndex).Cells("Status").Value = "0" Then 'File đang dùng
                    dataGridViewFiles.Rows(e.RowIndex).Cells("FileStatus").ToolTipText = "File đang nhập liệu"
                    bcx.Image = imageList1.Images("SecMedium")
                    'DataGridViewCellStyle1.ForeColor = Color.Gray ' System.Drawing.SystemColors.ControlText
                    'dataGridViewFiles.Rows(e.RowIndex).DefaultCellStyle = DataGridViewCellStyle1
                ElseIf dataGridViewFiles.Rows(e.RowIndex).Cells("Status").Value = "1" Then 'File hoàn thành
                    dataGridViewFiles.Rows(e.RowIndex).Cells("FileStatus").ToolTipText = "File đã làm xong"
                    bcx.Image = imageList1.Images("SecLow")
                    DataGridViewCellStyle1.ForeColor = Color.Gray ' System.Drawing.SystemColors.ControlText
                    dataGridViewFiles.Rows(e.RowIndex).DefaultCellStyle = DataGridViewCellStyle1
                End If
                bcx.Text = " " 'Gán text = " " để hình canh giữa
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

#End Region

#End Region

    Public Sub FormatDataGridView()
        Dim hideColumns As New List(Of String)({"Id_File", "Status"})
        Dim frozenColumnName As String = "FileNo"
        Dim renameColumns As New Dictionary(Of String, String)
        renameColumns.Add("UserName", "Staff")
        renameColumns.Add("CustomerName", "Customer")
        'Nếu là hàng xuất
        If _enumFILE = enumFILE.Export Then
            renameColumns.Add("Company", "Shipper")
            renameColumns.Add("ForeignCompany", "Consignee")
        Else
            renameColumns.Add("Company", "Consignee")
            renameColumns.Add("ForeignCompany", "Shipper")
        End If

        CViewer.FormatDataGridView(dataGridViewFiles, hideColumns, renameColumns, frozenColumnName)

    End Sub

    Public Sub BindingDataGridView(Optional ByVal indexRow As Integer = -1)
        'Lấy danh sách các File thuộc _enumFILE (hàng nhập hoặc hàng xuất)
        'Nếu chưa có lọc thì mặc định load tất cả
        Dim query = _ucSearchFiles.SelectCustomAllRecord()
        'If query Is Nothing Then
        '    query = _objFileController.SelectCustomAllRecord(_enumFILE)
        'End If

        Dim source As New BindingSource
        source.DataSource = query
        dataGridViewFiles.DataSource = source
        BindingNavigator1.BindingSource = source

        If indexRow < 0 Then
            indexRow = 0
        End If

        'Set current row
        If dataGridViewFiles.Rows.Count > 0 Then
            'dataGridViewFiles.Rows(indexRow).Selected = True
            'dataGridViewFiles.FirstDisplayedScrollingRowIndex = indexRow
            For Each col As DataGridViewColumn In dataGridViewFiles.Columns
                If col.Visible Then
                    dataGridViewFiles.CurrentCell = dataGridViewFiles.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next
        Else
            If _ucFileHBLGridView IsNot Nothing Then
                _ucFileHBLGridView.DataGridView.Rows.Clear()
            End If
            If dgContainers IsNot Nothing Then
                dgContainers.Rows.Clear()
            End If

            If dtgBuying IsNot Nothing Then
                dtgBuying.Rows.Clear()
            End If

            If gridSelling IsNot Nothing Then
                gridSelling.Rows.Clear()
            End If

        End If
    End Sub

    Private Sub dataGridViewFiles_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGridViewFiles.CellDoubleClick
        btnEdit_Click(Nothing, Nothing)
    End Sub

    Private Sub LoadCurrentTab()
        'If SuperTabControlFile.SelectedTab.Name = "SuperTabItemMBL" And dataGridViewFiles.CurrentRow.Index <> currRow Then
        '    'Load MBL
        '    If _ucFileMBLGridView Is Nothing Then
        '        InitFileMBLDataGridView()
        '    End If
        '    _ucFileMBLGridView.BindingDataGridView(_objFile)
        'ElseIf SuperTabControlFile.SelectedTab.Name = "SuperTabItemHBL" And dataGridViewFiles.CurrentRow.Index <> currRow Then

        'Kiểm tra xem nếu thay đổi row hoặc tab thì reload lại data
        If dataGridViewFiles.CurrentRow.Index <> currRow Or _
                SuperTabControlFile.SelectedTabIndex <> currTab Then
            If SuperTabControlFile.SelectedTab.Name = "SuperTabItemHBL" Then
                'Load HBL
                If _ucFileHBLGridView Is Nothing Then
                    InitHBLDataGridView()
                End If
                _ucFileHBLGridView.BindingDataGridView(_objFile)
            ElseIf SuperTabControlFile.SelectedTab.Name = "SuperTabItemContainer" Then
                '--------------------Thanh chỉnh sửa ngày 9/12/2013-------
                'load container
                BindingContainerDataGridView(_objFile)
            ElseIf SuperTabControlFile.SelectedTab.Name = "SuperTabItemBuyingSelling" Then
                'load buying
                BindGridBuying(_objFile.ID_File)
                'load selling
                BindingSellingRate(_objFile)
                '-------------------hết phần Thanh làm ngày 9/12/2013
            End If
        End If

    End Sub


    Private Sub dataGridViewFiles_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dataGridViewFiles.CurrentCellChanged
        If dataGridViewFiles.CurrentRow IsNot Nothing Then
            Dim id_file As Integer = dataGridViewFiles.CurrentRow.Cells("ID_File").Value
            _objFile = _objFileController.SelectRecordById(id_file)

            LoadCurrentTab()

            currRow = dataGridViewFiles.CurrentRow.Index


            If dataGridViewFiles.CurrentRow.Cells("Status").Value = "-1" Then
                btnDel.Text = "Uncancel"
                ButtonItemCancel.Text = "Uncancel"
            Else
                btnDel.Text = "Cancel"
                ButtonItemCancel.Text = "Cancel"
            End If
        End If
    End Sub
#End Region

#Region "Commands"

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            Dim fileNo As String = dataGridViewFiles.CurrentRow.Cells("FileNo").Value
            Dim file_id As Integer = dataGridViewFiles.CurrentRow.Cells("ID_File").Value
            Dim objFileControl As New ucFile(Me, file_id)

            If _enumFILE = enumFILE.Export Then
                _objFormMain.AddNewDockContainerItem("ExportFile" + fileNo, "Export File " + fileNo, objFileControl)
            Else
                _objFormMain.AddNewDockContainerItem("ImportFile" + fileNo, "Import File " + fileNo, objFileControl)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
       
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            Dim objFileControl As New ucFile(Me, _enumFILE)
            objFileControl.FillFormHeader(-1)
            If _enumFILE = enumFILE.Export Then
                _objFormMain.AddNewDockContainerItem("NewExportFile", "New Export File", objFileControl)
            Else
                _objFormMain.AddNewDockContainerItem("NewImportFile", "New Import File", objFileControl)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        'Try
        '    Dim fileType As String
        '    If _objFile.IsExport Then
        '        fileType = "Export"
        '    Else
        '        fileType = "Import"
        '    End If
        '    If MessageBox.Show(String.Format("Bạn thật sự muốn xóa {0} FileNo {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
        '        Dim indexRow As Integer = dataGridViewFiles.CurrentRow.Index - 1
        '        _objFileController.Delete(_objFile)
        '        BindingDataGridView(indexRow)
        '    End If
        'Catch ex As Exception
        '    MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        'End Try

        Try
            Dim fileType As String
            If _objFile.IsExport Then
                fileType = "Export"
            Else
                fileType = "Import"
            End If
            Dim indexRow As Integer = dataGridViewFiles.CurrentRow.Index
            If btnDel.Text = "Cancel" Then
                If MessageBox.Show(String.Format("Bạn muốn hủy {0} File {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    _objFileController.Cancel(_objFile, True)
                    btnDel.Text = "Uncancel"
                End If
            Else
                If MessageBox.Show(String.Format("Bạn muốn phục hồi lại {0} File {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    _objFileController.Cancel(_objFile, False)
                    btnDel.Text = "Cancel"
                End If

            End If
            BindingDataGridView(indexRow)
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        Dim indexRow As Integer = -1
        If dataGridViewFiles.CurrentRow IsNot Nothing Then
            indexRow = dataGridViewFiles.CurrentRow.Index
        End If
        BindingDataGridView(indexRow)
        _ucSearchFiles.btnCancel.PerformClick()
    End Sub
#End Region

#Region "Search Commands"
    'Private _ucSearchFiles As New ucSearchFiles()
    Private Sub InitSearchUserControl()
        _ucSearchFiles.InitControl(_enumFILE, _objFileController)
        _ucSearchFiles.Dock = DockStyle.Fill
        _ucSearchFiles.btnSearchEvent_Click = New EventHandler(AddressOf btnSearch_Click)
        _ucSearchFiles.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        PanelDockContainerSearch.Controls.Add(_ucSearchFiles)
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        BindingDataGridView()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        BindingDataGridView()
    End Sub
#End Region

    '#Region "FileMBL User Control"
    '    Private _objFileMBLController As New FileMBLController
    '    ''' <summary>
    '    ''' Khởi tạo thông tin user control MBL datagridview
    '    ''' </summary>
    '    ''' <remarks></remarks>
    '    Private Sub InitFileMBLDataGridView()
    '        _ucFileMBLGridView = New ucFileMBLGridView()
    '        _ucFileMBLGridView.Dock = DockStyle.Fill
    '        SuperTabControlPanelMBL.Controls.Add(_ucFileMBLGridView)
    '        '_ucFileMBLGridView.dataGridViewXMBL_CurrentCellChangedEvent = New EventHandler(AddressOf dataGridViewXFileMBL_CurrentCellChanged)
    '    End Sub

    '    'Private Sub dataGridViewXFileMBL_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    '    If _ucFileMBLGridView.DataGridView.CurrentRow IsNot Nothing Then
    '    '        _objFileMBL = _objFileMBLController.SelectRecordById(_ucFileMBLGridView.DataGridView.CurrentRow.Cells("ID_FileMBL").Value)
    '    '        'Nếu chưa khởi tạo usercontrol
    '    '        If _ucFileHBLGridView Is Nothing Then
    '    '            InitHBLDataGridView()
    '    '        End If
    '    '        _ucFileHBLGridView.BindingDataGridView(_objFileMBL)
    '    '    End If
    '    'End Sub
    '#End Region

#Region "FileHBL User Control"
    ''' <summary>
    ''' Khởi tạo thông tin user control HBL datagridview
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitHBLDataGridView()
        _ucFileHBLGridView = New ucFileHBLGridView(_objFile.IsExport)
        _ucFileHBLGridView.Dock = DockStyle.Fill
        SuperTabControlPanelHBL.Controls.Add(_ucFileHBLGridView)
    End Sub
#End Region

#Region "FileContainer User Control"
    ''' <summary>
    ''' Khởi tạo thông tin containers theo file
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub BindingContainerDataGridView(ByVal file As tblFile)
        'đọc danh sách các container của file theo idFile
        Dim ctrlCont As New CContainerController
        Dim q As IQueryable = ctrlCont.SelectContsByFile(file.ID_File)
        dgContainers.DataSource = q
        dgContainers.ReadOnly = True
    End Sub
#End Region

#Region "Thanh"
    Private Sub BindingSellingRate(ByVal file As tblFile)
        'bind danh sách các hbl của file
        cboHBL.DataSource = Nothing
        CViewer.BindHBLsToComboBox(cboHBL, _objFile.ID_File)
        Dim idHbl As Integer = -1
        Try
            If (cboHBL.Items.Count > 0) Then
                cboHBL.SelectedIndex = 0
            End If
            idHbl = cboHBL.SelectedValue
        Catch ex As Exception
        End Try
        'CViewer.BindGridSelling(gridSelling, idHbl, cboCurr)
        'gridSelling.ReadOnly = True
    End Sub
    Public Sub BindGridBuying(ByVal _idFile As Integer)
        'fill combo
        'Dim uti As New Utilities
        'uti.FillCurrencyCombo(EditcbCurrency)
        'Dim mBR As New MBuyingRate
        'Dim query = mBR.getFileFeeList(_idFile)
        Dim db As New TanNamChinhDataContext
        Dim query = From p In db.tblFileFees
                    Where p.ID_File = _idFile And p.tblFee.IsActive = True And p.UnitPrice > 0
                    Order By p.tblFee.Rank
                    Select p.tblFee.FeeName, p.UnitPrice, p.Quantity, p.Price, p.tblCurrency.Code, p.InvoiceNo, p.Description
        
        dtgBuying.DataSource = query

        With dtgBuying.Columns("Quantity")
            .HeaderText = "Qty"
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        End With
        With dtgBuying.Columns("UnitPrice")
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .DefaultCellStyle.Format = "#,###.####"
        End With
        With dtgBuying.Columns("Price")
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .DefaultCellStyle.Format = "#,###.####"
        End With
        dtgBuying.Columns("Code").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    End Sub
    Private Sub cboHBL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboHBL.SelectedIndexChanged
        Try
            Dim idHBL As Integer = cboHBL.SelectedValue()
            'CViewer.BindGridSelling(gridSelling, idHBL, cboCurr)
            Dim db As New TanNamChinhDataContext
            Dim query = From p In db.tblSellingFees
                        Where p.ID_HBL = idHBL And p.tblFee.IsActive = True And p.UnitPrice > 0
                        Order By p.tblFee.Rank
                        Select p.tblFee.FeeName, p.UnitPrice, p.Quantity, p.Price, p.tblCurrency.Code, p.Description

            gridSelling.DataSource = query
            With gridSelling.Columns("Quantity")
                .HeaderText = "Qty"
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With
            With gridSelling.Columns("UnitPrice")
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.Format = "#,###.####"
            End With
            With gridSelling.Columns("Price")
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.Format = "#,###.####"
            End With
            gridSelling.Columns("Code").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        Catch ex As Exception
        End Try
    End Sub
    'Private Sub FormatGridBuying()
    '    gridBuying.AllowUserToAddRows = False
    '    gridBuying.AllowUserToDeleteRows = False
    '    gridBuying.Columns("ID_FileFee").Visible = False
    '    gridBuying.Columns("FeeName").Width = 60
    '    gridBuying.Columns("UnitPrice").Width = 60
    '    gridBuying.Columns("UnitPrice").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    '    gridBuying.Columns("UnitPrice").DefaultCellStyle.Format = "#,##0.##"
    '    gridBuying.Columns("Quantity").Width = 30
    '    gridBuying.Columns("Quantity").HeaderText = "Qty"
    '    gridBuying.Columns("Quantity").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    '    gridBuying.Columns("Quantity").DefaultCellStyle.Format = "#,##0.##"
    '    gridBuying.Columns("Price").Width = 80
    '    gridBuying.Columns("Price").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    '    gridBuying.Columns("Price").DefaultCellStyle.Format = "#,##0.##"
    '    gridBuying.Columns("Code").Width = 60
    '    gridBuying.Columns("Code").HeaderText = "Currency"
    '    gridBuying.Columns("Description").Width = 200
    '    gridBuying.ScrollBars = 3
    'End Sub
    Private Sub btPrintAN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrintAN.Click
        'If (_objFile.IsExport = True) Then
        '    MessageBox.Show("Chức năng chỉ dành cho hàng nhập!")
        '    Exit Sub
        'Else
        'lấy thông tin là HBL nào đang được chọn
        Dim hblCtrl As New CHBLController
        Dim hbl As tblHBL = Nothing
        Try
            Dim gridHBL As DevComponents.DotNetBar.Controls.DataGridViewX = _ucFileHBLGridView.DataGridView
            Dim curRowHBL As DataGridViewRow = gridHBL.CurrentRow
            Dim idHBL As Integer = CInt(curRowHBL.Cells("ID_HBL").Value)
            hbl = hblCtrl.SelectRecordByID(idHBL)
        Catch ex As Exception
            MessageBox.Show("Không chọn được HBL để in Arrival Note!")
        End Try
        If (hbl IsNot Nothing) Then
            CViewer.PrintAN(hbl)
        End If
    End Sub
#End Region
    
    Private Sub btnPaymentVoucher_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPaymentVoucher.Click
        ''Kiểm tra xem có tồn tại phiếu chi chưa
        'Dim mpv As New MPaymentVoucher
        'Dim ise = mpv.ExistPaymentVoucher(_objFile.ID_File)
        ''Nếu đã có thì mở form quản lý ra xem
        'If ise = True Then

        If _enumFILE = enumFILE.Import Then
            frmMain.AddNewDockContainerItem("PaymentVoucher", "Payment Voucher", New ucPaymentVoucherNew(_objFile.ID_File, False))
        Else
            frmMain.AddNewDockContainerItem("PaymentVoucher", "Payment Voucher", New ucPaymentVoucherNew(_objFile.ID_File, True))

        End If

        'Else
        '    'Nếu chưa mới hiển thị form tạo cái mới
        '    frmMain.AddNewDockContainerItem("CreatePayment", "Create Payment Voucher", New ucOnePaymentVoucher(_objFile.ID_File, 0))

        'End If

    End Sub

    Private Sub SuperTabControlFile_SelectedTabChanged(ByVal sender As System.Object, ByVal e As DevComponents.DotNetBar.SuperTabStripSelectedTabChangedEventArgs) Handles SuperTabControlFile.SelectedTabChanged
        If dataGridViewFiles.CurrentRow IsNot Nothing Then
            LoadCurrentTab()
            currTab = SuperTabControlFile.SelectedTabIndex
        End If
        
    End Sub

   
    Private Sub btnRecapEX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecapEX.Click


        'MsgBox(dataGridViewFiles.RowCount)
        'MsgBox(dataGridViewFiles.Rows(0).Cells("ID_File").Value)

        Dim list_File As New List(Of Integer)
        For i As Integer = 0 To dataGridViewFiles.RowCount - 1
            list_File.Add(dataGridViewFiles.Rows(i).Cells("ID_File").Value)
        Next

        'RECAP EXPORT
        Dim db As New TanNamChinhDataContext
        Dim ListFile = (From p In db.tblFiles
                        Where p.IsExport = _enumFILE And list_File.Contains(p.ID_File)
                       Select p).ToArray

        If _enumFILE = enumFILE.Export Then
            CModule_Sy.ToExcel_RECAP_EXPORT(ListFile)
        Else
            CModule_Sy.ToExcel_RECAP_IMPORT(ListFile)
        End If

    End Sub

    Private Sub ButtonItemRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemRefresh.Click
        btnRefresh.PerformClick()
    End Sub

    Private Sub ButtonItemAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemAdd.Click
        btnAdd.PerformClick()
    End Sub

    Private Sub ButtonItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItem2.Click
        btnEdit.PerformClick()
    End Sub

    Private Sub ButtonItemCopyFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemCopyFile.Click
        Try
            Dim objCopyFile As tblFile = _objFileController.InsertByCopyFile(_objFile)

            '====================================================
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Add, String.Format("File {0}", objCopyFile.FileNo))

            btnRefresh.PerformClick()
            BindingDataGridView(0)
            _ucSearchFiles.btnCancel.PerformClick()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub ButtonItemCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemCancel.Click
        Try
            Dim fileType As String
            If _objFile.IsExport Then
                fileType = "Export"
            Else
                fileType = "Import"
            End If
            Dim indexRow As Integer = dataGridViewFiles.CurrentRow.Index
            If ButtonItemCancel.Text = "Cancel" Then
                If MessageBox.Show(String.Format("Bạn muốn hủy {0} FileNo {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    _objFileController.Cancel(_objFile, True)
                    ButtonItemCancel.Text = "Uncancel"
                End If
            Else
                If MessageBox.Show(String.Format("Bạn muốn bỏ hủy {0} FileNo {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    _objFileController.Cancel(_objFile, False)
                    ButtonItemCancel.Text = "Cancel"
                End If

            End If
            BindingDataGridView(indexRow)
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private Sub ButtonItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItem6.Click
        btnPaymentVoucher.PerformClick()
    End Sub

    Private Sub ButtonItemExportRecap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemExportRecap.Click
        btnRecapEX.PerformClick()
    End Sub

    Private Sub ButtonItemArrivalNoteReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        btPrintAN.PerformClick()
    End Sub

    Private Sub gridEdit_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs)
        MessageBox.Show("Error happened " _
         & e.Context.ToString())

        If (e.Context = DataGridViewDataErrorContexts.Commit) _
            Then
            MessageBox.Show("Commit error")
        End If
        If (e.Context = DataGridViewDataErrorContexts _
            .CurrentCellChange) Then
            MessageBox.Show("Cell change")
        End If
        If (e.Context = DataGridViewDataErrorContexts.Parsing) _
            Then
            MessageBox.Show("parsing error")
        End If
        If (e.Context = _
            DataGridViewDataErrorContexts.LeaveControl) Then
            MessageBox.Show("leave control error")
        End If

        If (TypeOf (e.Exception) Is ConstraintException) Then
            Dim view As DataGridView = CType(sender, DataGridView)
            view.Rows(e.RowIndex).ErrorText = "an error"
            view.Rows(e.RowIndex).Cells(e.ColumnIndex) _
                .ErrorText = "an error"

            e.ThrowException = False
        End If
    End Sub

    Private Sub ButtonItemDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonItemDelete.Click
        Try
            If GeneralClassBAL._User.ID_User <> _objFile.ID_User And GeneralClassBAL._User.ID_Role <> enumROLE.ADMINISTRATOR Then
                MessageBox.Show("Chỉ admin hoặc người tạo file này mới có quyền xóa file")
                Exit Sub
            End If

            Dim fileType As String
            If _objFile.IsExport Then
                fileType = "Export"
            Else
                fileType = "Import"
            End If
            If MessageBox.Show(String.Format("Bạn thật sự muốn xóa {0} File {1}?", fileType, _objFile.FileNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                Dim indexRow As Integer = dataGridViewFiles.CurrentRow.Index - 1
                _objFileController.Delete(_objFile)

                '====================================================
                'Write log
                Dim objLogController As New LogController
                objLogController.Insert(enumAction.Delete, String.Format("File {0}", _objFile.FileNo))

                BindingDataGridView(indexRow)
            End If
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private Sub ButtonItemReceiptVoucher_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
 
    Private Sub btPrintDO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'lấy thông tin là HBL nào đang được chọn
        Dim hblCtrl As New CHBLController
        Dim hbl As tblHBL = Nothing
        Try
            Dim gridHBL As DevComponents.DotNetBar.Controls.DataGridViewX = _ucFileHBLGridView.DataGridView
            Dim curRowHBL As DataGridViewRow = gridHBL.CurrentRow
            Dim idHBL As Integer = CInt(curRowHBL.Cells("ID_HBL").Value)
            hbl = hblCtrl.SelectRecordByID(idHBL)
        Catch ex As Exception
            MessageBox.Show("Không chọn được HBL để in Delivery Order!")
        End Try
        If (hbl IsNot Nothing) Then
            CViewer.PrintDO(hbl)
        End If
    End Sub

    Private Sub dataGridViewFiles_ColumnSortModeChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dataGridViewFiles.ColumnSortModeChanged
        If e.Column.Name = "FileNo" Then

        End If
    End Sub
End Class
